use salvo::prelude::*;

/// Middleware that executes logic after the next handler (Post-processing)
#[allow(dead_code)]
#[handler]
async fn post_processing_middleware(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
    ctrl.call_next(req, depot, res).await;
    // Middleware that executes logic after the next handler (Post-processing)
}

/// Middleware implementing the onion model with pre and post logic
#[allow(dead_code)]
#[handler]
async fn onion_model_middleware(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
    // Middleware that executes logic before the matched handler (Pre-processing)   
    ctrl.call_next(req, depot, res).await;
    // Middleware that executes logic after the next handler (Post-processing)
}

/// Middleware that executes logic before the matched handler (Pre-processing)
#[allow(dead_code)]
#[handler]
async fn pre_processing_middleware(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
    //  Middleware that executes logic before the matched handler (Pre-processing)
    ctrl.call_next(req, depot, res).await;
}


/// Middleware to skip remaining handlers
#[allow(dead_code)]
#[handler]
async fn skip_handler_middleware(&self, _req: &mut Request, _depot: &mut Depot, _res: &mut Response, ctrl: &mut FlowCtrl) {
    // Middleware to skip remaining handlers
    ctrl.skip_rest();
}

/**
 * Middleware to print JWT Token
 * hoops可以接受不同数量的参数，并将其传递给中间件
 */
#[handler]
pub async fn print_jwt(req: &mut Request, _depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
    // 从请求头获取 Authorization 字段
    println!("==> Headers: {:#?}", req.headers());
    if let Some(auth_header) = req.headers().get("cookie") {
        let auth_str = auth_header.to_str().unwrap_or("");
        // 解析 Bearer Token
        if let Some(token) = auth_str.strip_prefix("Bearer ") {
            println!("Received JWT Token Bearer: {}", token);
        }

        if let Some(token) = auth_str.strip_prefix("jwt_token=") {
            println!("==> Received JWT Token jwt_token: {}", token);
        }
    }
    ctrl.call_next(req, _depot, res).await;
}
